package com.koron.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.koron.auth.aop.LoginLog;
import com.koron.auth.service.StaffService;
import com.koron.bean.app.AppSimpleBean;
import com.koron.bean.base.Response;
import com.koron.bean.system.org.OrgVo;
import com.koron.bean.system.staff.Constant;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.common.core.business.system.SystemCacheUtil;
import com.koron.common.core.business.workflow.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service("zsjAuthService")
@Slf4j
@RefreshScope
public class ZsjAuthServiceImpl {
        @Autowired
        StaffService staffService;

        @Value("${sso.redirectPage}")
        private String redirectPage;

        @Value("${sso.redirectWorkStationPage}")
        private String workStationPage;

        @Value("${sso.redirectUrl:null}")
        private String redirectUrl;

        @Value("${cas.ticket:null}")
        private String ticketUrl;



        //直接重定向到前台
        public void ssoLoginRedirect(String ticket, HttpServletRequest request, HttpServletResponse response) throws IOException {
            //在此判断如果用户只有一个租户、一个组织、一个身份，登录之后直接跳转到首页
            if (!StringUtils.isEmpty(ticket)) {

                Response msg = getAccountByTicket(ticket);

                // 查询条件字符串转对象，查询数据结果
                // ticket有错，可返回异常信息，前端可重定向到系统登录界面，也可在此用response.sendRedirect直接重定向到登录界面
                if (msg.getCode() != 0) {
                    response.setContentType("text/html; charset=UTF-8");
                    response.getWriter().println("未找到集团单点登录信息:" + ticket);
                    return;
                }
                String account = (String) msg.getData();
                if (StringUtils.isEmpty(account)) {
                    response.setContentType("text/html; charset=UTF-8");
                    response.getWriter().println("未找到集团单点登录信息:" + ticket);
                    return;
                }

                // 校验本系统用户表是否有对应账号
                Response res = staffService.queryStaffInfo(account);
                if (!(res.getCode() == 200 && res.getData() != null)) {
                    //setSSORedirectHeader(response);
                    response.setContentType("text/html; charset=UTF-8");
                    response.getWriter().println("系统没有该账号信息:" + account);
                    return;
                }

                EamUser eamUser = JSON.parseObject(JSON.toJSONString(res.getData()), EamUser.class);

                if (Objects.isNull(eamUser)) {
                    response.setContentType("text/html; charset=UTF-8");
                    response.getWriter().println("系统没有该账号信息:" + account);
                    return;
                }

                if (defaultInfo(eamUser, response)) {
                    return;
                }
            }

            log.info("auth 重定向前台页面:{}", redirectPage);
            response.sendRedirect(redirectPage + ticket);
        }


    @LoginLog
    public Response getSsoLoginUserInfo(String ticket, String account, HttpServletRequest request, HttpServletResponse response) throws IOException {

        EamUser eamUser;

        String token = null;

        if (StringUtils.isEmpty(account)) {
            //获取请求里面  原有的token信息. 若原来token是有效,则按照解析出来的账号信息查询最新权限数据返回前端
            token = request.getHeader(Constant.JWT_TOKEN);

            if (StringUtils.isNotEmpty(token)) {
                String preAccount = SystemCacheUtil.verifyToken(token);
                if (StringUtils.isNotEmpty(preAccount)) {
                    account = preAccount;
                } else {
                    //说明token失效,将token重置为null
                    token = null;
                }
            }

            if (!StringUtils.isEmpty(ticket)) {

                Response msg = getAccountByTicket(ticket);

                // 查询条件字符串转对象，查询数据结果
                // ticket有错，可返回异常信息，前端可重定向到系统登录界面，也可在此用response.sendRedirect直接重定向到登录界面
                if (msg.getCode() != 0) {
                    setSSORedirectHeader(response);
                    return Response.fail(msg.getDescription());
                }
                account = (String) msg.getData();
                if (StringUtils.isEmpty(account)) {
                    setSSORedirectHeader(response);
                    return Response.fail("未找到该账号登录oa信息");
                }
            }
        }

        if (StringUtils.isEmpty(account)) {
            log.error("登录账号为空");
            //响应设置 状态码及重定向地址,参数与前端约定. 302 redirecturl
            setSSORedirectHeader(response);
            return Response.fail("登录账号为空");
        }

        // 校验本系统用户表是否有对应账号
        Response res = staffService.queryStaffInfo(account);
        if (!(res.getCode() == 200 && res.getData() != null)) {
            setSSORedirectHeader(response);
            return Response.fail("系统没有该账号信息");
        }

        eamUser = JSON.parseObject(JSON.toJSONString(res.getData()), EamUser.class);

        //返回登录成功信息，前端可做跳转首页处理或者后台直接重定向到系统首页
        //cas认证通过，然后根据信息返回token
        if (StringUtils.isEmpty(token)) {
            token = SystemCacheUtil.getNewToken(eamUser.getAccount(), eamUser.getName());
        }

        List<String> userTokenList = new ArrayList<>();

        //redis拿出原来tokenList
        EamUser redisUser = SystemCacheUtil.getRedisUser(eamUser.getAccount());
        if (!Objects.isNull(redisUser) && CollectionUtils.isNotEmpty(redisUser.getTokenList())) {
            userTokenList = redisUser.getTokenList();
        }
        eamUser.setTokenList(userTokenList);
        SystemCacheUtil.cacheUserInfo(eamUser, token);

        if (response != null) {
            response.setHeader(Constant.JWT_TOKEN, token);
        }
        return Response.ok("登录成功", eamUser);
    }

        private void setSSORedirectHeader(HttpServletResponse response) {
            response.setHeader("redirecturl", redirectUrl);
            response.setStatus(HttpStatus.FOUND.value());
        }
    /* uma统一用户*/
    private Response getAccountByTicket(String ticket) {

        //ticket回调地址Constant.TICKET_APPID为应用标识本例摘自漏损管理应用应用标识为：inwlms （系统英文简写）
        String path = ticketUrl + ticket ;
        log.info("获取用户信息：{}", path);
        //ticket回调获取登录有效用户账户信息
        String jsonStr = HttpUtil.sendGet(path,"null");

        log.info("ticket验证返回数据:{}", jsonStr);
        if (StringUtils.isEmpty(jsonStr)||!StringUtils.contains(jsonStr,"loginName")) {
            return Response.fail("ticket获取用户信息失败");
        }

        StringBuilder stringBuilder = new StringBuilder(jsonStr);
        int right = stringBuilder.lastIndexOf("&#034;,&#034;passwordDate");
        int left = stringBuilder.indexOf("loginName&#034;:&#034;");
        Response msg = new Response();
        msg.setCode(0);
        msg.setData(stringBuilder.substring(left+22, right));
        return msg;
        }
        public Boolean defaultInfo(EamUser eamUser, HttpServletResponse response) throws IOException {

            List<OrgVo> orgVoList = eamUser.getOrgVoList();
            List<AppSimpleBean> appSimpleBeanList = eamUser.getAppSimpleBeanList();

            if (CollectionUtils.isNotEmpty(orgVoList) && orgVoList.size() == 1
                    && CollectionUtils.isNotEmpty(appSimpleBeanList)
                    && appSimpleBeanList.size() == 1) {

                //返回登录成功信息，前端可做跳转首页处理或者后台直接重定向到系统首页
                //cas认证通过，然后根据信息返回token
                String token = SystemCacheUtil.getNewToken(eamUser.getAccount(), eamUser.getName());

                List<String> userTokenList = new ArrayList<>();

                //redis拿出原来tokenList
                EamUser redisUser = SystemCacheUtil.getRedisUser(eamUser.getAccount());
                if (!Objects.isNull(redisUser) && CollectionUtils.isNotEmpty(redisUser.getTokenList())) {
                    userTokenList = redisUser.getTokenList();
                }
                eamUser.setTokenList(userTokenList);
                SystemCacheUtil.cacheUserInfo(eamUser, token);

                if (response != null) {
                    response.setHeader(Constant.JWT_TOKEN, token);
                }
                log.info("auth 重定向前台页面:{}", workStationPage);
                //附加上水司+组织
                StringBuilder sb = new StringBuilder();
                sb.append(token);
                sb.append("&currDs="+appSimpleBeanList.get(0).getAppMark());
                sb.append("&currOrg="+orgVoList.get(0).getId());

                response.sendRedirect(workStationPage + sb.toString());
                return true;
            }
            return false;
        }





}
